package sy10_4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8088);
        System.out.println("传输文件");

        while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            byte[] b = new byte[1024];
            int len = inputStream.read(b);
            System.out.println(new String(b, 0, len));

            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("传输文件".getBytes());


            File dir = new File("E:\\截图文件");
            if (!dir.exists()) {
                dir.mkdir();
            }
            String filename = "" + System.currentTimeMillis() + new Random().nextInt(10) + ".jpg";
            FileOutputStream fileOutputStream = null;

            fileOutputStream = new FileOutputStream(new File(dir, filename));
            while ((len = inputStream.read(b)) != -1) {

                fileOutputStream.write(b, 0, len);
            }
            fileOutputStream.close();

            outputStream.write("传输成功".getBytes());
            socket.close();
        }
    }
}
